﻿var WIDGETS = WIDGETS || {};

WIDGETS["menu-play-keyboard"] = function ($element) {

    var proto = {
        $element: $($element),
        $btnTime: $(),

        init: function () {
            this.discoverChildren();
            this.bindEvents();
            this.storeSelf();
        },

        discoverChildren: function () {
            this.$btnTime = this.$element.find(".btn.clock");
            this.$numKeys = this.$element.find(".btn.num");
        },

        bindEvents: function () {
            EVENTBROKER.keyTopic.on(TOPIC_EVENTS.key, this.onKey.bind(this));
            EVENTBROKER.keyTopic.on(TOPIC_EVENTS.keyDisable, this.onKeyDisable.bind(this));
            EVENTBROKER.keyTopic.on(TOPIC_EVENTS.keySwitch, this.onKeySwitch.bind(this));
            EVENTBROKER.matchTopic.on(TOPIC_EVENTS.matchTimerTick, this.onTimerTick.bind(this));
            EVENTBROKER.gameTopic.on(TOPIC_EVENTS.gameOptionsChanged, this._onGameOptionsChanged.bind(this));
        },

        storeSelf: function () {
            this.$element.data("menu-play-keyboard", this);
        },

        onKey: function (ev, key) {
            if (key == "clock") {
                UserOptions.current.timerVisible = !UserOptions.current.timerVisible;
                EVENTBROKER.gameTopic.trigger(TOPIC_EVENTS.gameOptionsChanged, UserOptions.current);
            }

            if (key.startsWith("pencil-")) {
                var isOn = key.endsWith("-on");
                this.setNumToSwitchMode(isOn);
            }
        },

        onKeyDisable: function (ev, key) {
            var args = CmdArgsHelper.GetSwitchArgsValue(key);
            this.$element.find(".btn" + "." + args.key).toggleClass("disabled", !args.isOn);
        },

        onKeySwitch: function (ev, key) {
            var args = CmdArgsHelper.GetSwitchArgsValue(key);
            this.$element.find(".btn" + "." + args.key).toggleClass("on", args.isOn);
        },

        setNumToSwitchMode: function (isSwitchMode) {
            this.$numKeys.toggleClass("switch", isSwitchMode);
        },

        onTimerTick: function (ev, time) {
            var timeStr = UTIL.string.toHMM(time);
            this.$btnTime.find(".time").text(timeStr);
        },

        _onGameOptionsChanged: function (ev, userOptions) {
            this.$btnTime.toggleClass("show-time", userOptions.timerVisible);
        }
    }

    proto.init();

    return proto;
}
